package com.eduction.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.eduction.bean.SessionUser;
import com.eduction.common.AppConfig;
import com.eduction.common.ReturnCode;
import com.eduction.common.UploadUtil;
import com.eduction.modules.system.entity.SchoolItemData;
import com.eduction.modules.system.entity.SchoolPointMap;
import com.eduction.modules.target.entity.MonitorSeeMap;
import com.eduction.resource.BaseController;
import com.eduction.service.MonitorSeeMapService;
import com.eduction.service.SchoolItemDataService;
import com.eduction.service.SchoolPointMapService;
import com.eduction.service.impl.SchoolService;

/**
 * 学校数据填报接口
 * @author kuaik
 *
 */
@Controller
@RequestMapping("/dataReport")
public class SchoolDataReportController extends BaseController{
	private static final Logger log = Logger.getLogger(ExpertAllocationController.class);
	@Autowired
	private SchoolItemDataService schoolItemDataService;
	@Autowired
	private MonitorSeeMapService monitorSeeMapService;
	@Autowired
	private SchoolPointMapService schoolPointMapService;
	@Autowired
	private SchoolService schoolService;
	@Value("${doc.path}")
	private String docPath;
	@Autowired
	private UploadUtil uploadUtil;
	@Value("${image_allow_files}")
	private String image_allow_files;
	/**
	 * 保存测评点分项
	 */
	@RequestMapping(value = "/saveMonitor" ,produces = MediaType.APPLICATION_JSON_VALUE+";charset=UTF-8", method=RequestMethod.POST)
	@ResponseBody
	public ResponseEntity<String> addCRMap(HttpServletRequest request,@RequestBody Map<String,String> map){
		String user_type = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
		if(StringUtils.isEmpty(user_type)){
			return toResponse(null,ReturnCode.FAIL,"暂无权限！");
		}

		String sid = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_KEY);
		if(sid == null){
			return toResponse(null, ReturnCode.NOLOGIN, "未登录");
		}
		String item = map.get("itemId");
		String value = map.get("value");
		String createTime =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
		Calendar cal=Calendar.getInstance();
        int y=cal.get(Calendar.YEAR);
        
        String[] itemList = item.split("#");
		String[] valueList = value.split("#");
		try {
			for (int i = 0; i < valueList.length; i++) {
				SchoolItemData sd = schoolItemDataService.querySchoolItemData(sid, itemList[i],y);
				if(sd == null){
					SchoolItemData sd1 = new SchoolItemData();
					sd1.setS_create_time(createTime);
					sd1.setS_year(y);
					sd1.setS_item_id(itemList[i]);
					sd1.setS_value(valueList[i]);
					sd1.setS_school_id(sid);
					schoolItemDataService.saveSchoolItemData(sd1);
				}else{
					sd.setS_create_time(createTime);
					sd.setS_year(y);
					sd.setS_item_id(itemList[i]);
					sd.setS_value(valueList[i]);
					sd.setS_school_id(sid);
					schoolItemDataService.saveSchoolItemData(sd);
				}
			}
			//保存评测点填报状态
			MonitorSeeMap m = this.monitorSeeMapService.queryMonitorSeeMapByPid(itemList[0]);
			SchoolPointMap schoolPointMap = this.schoolPointMapService.queryOneByPid(m.getP_monitor_id()); 
			if(schoolPointMap == null){
				schoolPointMap = new SchoolPointMap();
				schoolPointMap.setPointId(m.getP_monitor_id());
				schoolPointMap.setSchoolId(sid);
				schoolPointMap.setState("1");
				this.schoolPointMapService.saveSchoolPointMap(schoolPointMap);
			}
			return toResponse(null,ReturnCode.SUCCESS,"保存成功");
		}  catch (Exception e) {
			log.error(e);
			return toResponse(null, ReturnCode.FAIL, "保存失败");
		}
	}
	
	
	/**
	 * 文件上传
	 * @param Filedata
	 * @return
	 */
	@RequestMapping(value="/uploadfile" ,produces = MediaType.TEXT_HTML_VALUE+";charset=UTF-8", method=RequestMethod.POST)
	@ResponseBody
	public ResponseEntity<String> uploadFile(@RequestParam("file")MultipartFile filedata,HttpServletRequest request){
		try {
			String user_type = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
			if(StringUtils.isEmpty(user_type)){
				return toResponse(null,ReturnCode.FAIL,"暂无权限！");
			}
			String sid = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_KEY);
			//String returnDatasUrl = null;
	  		
	  		/*//取得可上传的文件类型  
	  		List<String>fileTypes = arrayToList(appconfig.getFileType().split(","));*/
	  		
	  		String fileName = filedata.getOriginalFilename();  
	  		//获取上传文件类型的扩展名,先得到.的位置，再截取从.的下一个位置到文件的最后，最后得到扩展名  
	  		String ext = fileName.substring(fileName.lastIndexOf(".")+1,fileName.length());   
	  		//对扩展名进行小写转换  
	  		ext = ext.toLowerCase();  
	  		//新的文件名
	  		String newFileName = new SimpleDateFormat("yyyyMMddHHmmssms").format(new Date()) + 
	  				(int)(Math.random()*10000) + "." + ext;
	  		File file = null;
	  		if(!"pdf".equals(ext)){
	  			return toResponse(null,ReturnCode.FILE_TYPE_NOT_MATCH,"该文件类型不允许");
	  		}
	  		Long examSize=filedata.getSize();
	  		if(1.0*examSize/1024/1024> 3072 ){
	  			return toResponse(null,ReturnCode.FILE_SIZE_TOO_LONG,"文件大小超出限定上限");
	  		}
	  		
	  		/*Calendar cal=Calendar.getInstance();
            int y=cal.get(Calendar.YEAR);
            int m=cal.get(Calendar.MONTH)+1;
            int d=cal.get(Calendar.DATE);
            Long nowTime=new Date().getTime();*/
            String pathbig=docPath+"/schoolData_file/"+sid+"/"+newFileName;
            file=new File(pathbig);
     		if(!file.exists()){
     			file.getParentFile().mkdirs();
     			file.createNewFile();
     		}
     		filedata.transferTo(file);
				
		    //returnDatasUrl =docPath+y+"/"+m+"/"+d+"/"+nowTime+"/"+fileName;
			return toResponse(newFileName,ReturnCode.SUCCESS,null);
		} catch (Exception e) {
			log.error("文件上传失败", e);
			return toResponse(null,ReturnCode.FAIL,"文件上传失败");
		}
	}
	
	
	/**
	 * 图片上传
	 * @param Filedata
	 * @return
	 */
	@RequestMapping(value="/uploadpic" ,produces = MediaType.TEXT_HTML_VALUE+";charset=UTF-8", method=RequestMethod.POST)
	@ResponseBody
	public ResponseEntity<String> uploadPhoto(@RequestParam("file")MultipartFile filedata,HttpServletRequest request){
		String user_type = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
		if(StringUtils.isEmpty(user_type)){
			return toResponse(null,ReturnCode.FAIL,"暂无权限！");
		}

		//String returnDatasUrl = null;
  		String sid = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_KEY);
  		//取得可上传的文件类型  
  		String[] types = image_allow_files.split(",");
  		
  		String fileName = filedata.getOriginalFilename();  
  		//获取上传文件类型的扩展名,先得到.的位置，再截取从.的下一个位置到文件的最后，最后得到扩展名  
  		String ext = fileName.substring(fileName.lastIndexOf(".")+1,fileName.length());  
  		//对扩展名进行小写转换  
  		ext = ext.toLowerCase();  
  		//新的文件名
  		String newFileName = new SimpleDateFormat("yyyyMMddHHmmssms").format(new Date()) + 
  				(int)(Math.random()*10000) + "." + ext;
  		File file = null;
  		try {
			for(String s:types){
				if(s.equals(ext)){
					// Calendar cal=Calendar.getInstance();
			        /* int y=cal.get(Calendar.YEAR);
			         int m=cal.get(Calendar.MONTH)+1;
			         int d=cal.get(Calendar.DATE);*/
			         String pathbig=docPath+"/schoolData_img/"+sid+"/"+newFileName;
			         file=new File(pathbig);
			 		if(!file.exists()){
			 			file.getParentFile().mkdirs();
			 			file.createNewFile();
			 		}
			 		filedata.transferTo(file);
			        //returnDatasUrl = y+"/"+m+"/"+d+"/"+newFileName;
			 		return toResponse(newFileName, ReturnCode.SUCCESS, "上传图片成功");
				}
			}
			return toResponse(null, ReturnCode.FAIL, "图片类型不符");
		} catch (IllegalStateException e) {
			log.error(e);
			return toResponse(null, ReturnCode.FAIL, "上传图片失败");
		} catch (IOException e) {
			log.error(e);
			return toResponse(null, ReturnCode.FAIL, "上传图片失败");
		}
	}
	
	/**
	 * 文件下载
	 * @param
	 * @return
	 */
	@RequestMapping(value="/downFile" ,produces = MediaType.TEXT_HTML_VALUE+";charset=UTF-8")
	@ResponseBody
	public void downFile(HttpServletRequest request,HttpServletResponse response,@RequestParam String fileName){
		String schoolId = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_KEY);
		BufferedInputStream bis = null;  
	    BufferedOutputStream bos = null;
		String user_type = (String) request.getSession().getAttribute(SessionUser.SESSION_USER_TYPE);
		if(StringUtils.isEmpty(user_type)){
			return;
		}
	    try {
			//获取项目根目录
			//String ctxPath = request.getSession().getServletContext().getRealPath("");  
			
			//获取下载文件路径
			String downLoadPath = docPath+"/schoolData_file/"+schoolId+"/"+ fileName;  
  
			//获取文件的长度
			long fileLength = new File(downLoadPath).length();  

			//设置文件输出类型
			response.setContentType("application/octet-stream");
			response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1")); 
			//告诉浏览器文件长度
			response.setHeader("Content-Length", String.valueOf(fileLength));  
			//获取输入流
			bis = new BufferedInputStream(new FileInputStream(downLoadPath));  
			//输出流
			bos = new BufferedOutputStream(response.getOutputStream());  
			byte[] buff = new byte[2048];  
			int bytesRead;  
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {  
			  bos.write(buff, 0, bytesRead);  
			}
		} catch (Exception e) {
			log.error(e);
		}finally{
			try {
				bis.close();
				bos.close();
			} catch (IOException e) {
				log.info("文件下载异常", e);
			}
		}  
	}
}
